<template>
  <div class="login">
    <div class="login-wrap">
      <div class="title">{{ $t('login.register') }}</div>
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        class="login-form"
        size="medium"
      >
        <el-form-item prop="phone" class="item-from">
          <el-input
            v-model="ruleForm.phone"
            type="text"
            autocomplete="off"
            :placeholder="$t('login.inputPhone')"
          />
        </el-form-item>

        <el-form-item prop="password" class="item-from">
          <el-input
            ref="passwordType"
            v-model="ruleForm.password"
            :type="passwordType"
            autocomplete="off"
            minlength="6"
            maxlength="20"
            :placeholder="$t('login.inputPwd')"
          />
          <span class="show-pwd" @click="showPwd('passwordType')">
            <svg-icon
              :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>
        <el-form-item prop="passwords" class="item-from">
          <el-input
            ref="passwordsType"
            v-model="ruleForm.passwords"
            :type="passwordsType"
            autocomplete="off"
            minlength="6"
            maxlength="20"
            :placeholder="$t('login.inputPwdAgain')"
          />
          <span class="show-pwd" @click="showPwd('passwordsType')">
            <svg-icon
              :icon-class="passwordsType === 'password' ? 'eye' : 'eye-open'"
            />
          </span>
        </el-form-item>

        <el-form-item prop="code" class="item-from code">
          <el-input
            v-model="ruleForm.code"
            minlength="6"
            maxlength="6"
            :placeholder="$t('login.inputCode')"
          />
          <button
            class="block codebtn"
            type="button"
            :disabled="codeButtonStatus.status"
            @click="getSms"
          >
            <span>{{ codeButtonStatus.text }}</span>
          </button>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="login-btn block"
            @click="submitForm"
          >{{ $t('login.register') }}</el-button>
        </el-form-item>
      </el-form>
      <div class="tab">
        <span style="color:#409eff;" @click="toggle">
          {{ $t('login.returnLogin') }}>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import {
  stripscript,
  validatePass,
  validatePhone,
  validateVCode,
} from '@/utils/validate';
import register from '@/api/register';
import code from '@/api/code';
import { dataToBase64 } from '@/utils/';

export default {
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(this.$t('login.inputPhone')));
      } else if (validatePhone(value)) {
        callback(new Error(this.$t('login.phoneError')));
      } else {
        callback(); // true
      }
    };
    // 验证密码
    const validatePassword = (rule, value, callback) => {
      // 过滤后的数据
      this.ruleForm.password = stripscript(value);
      value = this.ruleForm.password;
      if (value === '') {
        callback(new Error(this.$t('login.pInputPwd')));
        return;
      } else {
        if (this.ruleForm.passwords !== '') {
          this.$refs.ruleForm.validateField('passwords');
        }
        if (validatePass(value)) {
          callback(new Error(this.$t('login.pwdTip')));
        } else {
          callback();
        }
      }
    };
    // 验证重复密码
    const validatePasswords = (rule, value, callback) => {
      // 过滤后的数据
      this.ruleForm.passwords = stripscript(value);
      value = this.ruleForm.passwords;
      if (value === '') {
        callback(new Error(this.$t('login.inputPwdAgain')));
      } else if (value !== this.ruleForm.password) {
        callback(new Error(this.$t('login.pwdsError')));
      } else {
        callback();
      }
    };

    // 验证验证码
    const validateCode = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error(this.$t('login.inputCode')));
      } else if (validateVCode(value)) {
        return callback(new Error(this.$t('login.codeError')));
      } else {
        callback();
      }
    };
    return {
      //   表单绑定数据
      ruleForm: {
        phone: '',
        password: '',
        passwords: '',
        code: '',
      },
      timer: null,
      codeButtonStatus: {
        status: false,
        text: this.$t('login.getCode'),
      },
      passwordType: 'password',
      passwordsType: 'password',
      model: 'login',
      rules: {
        phone: [
          { required: true, validator: validateUsername, trigger: 'blur' },
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' },
        ],
        passwords: [
          { required: true, validator: validatePasswords, trigger: 'blur' },
        ],
        code: [{ required: true, validator: validateCode, trigger: 'blur' }],
      },
      bid: '',
      code: '',
    };
  },
  methods: {
    /**
     * 清除表单数据
     */
    resetFromData() {
      this.$refs.ruleForm.resetFields();
      this.clearCountDown();
    },
    /**
     * 密码显示
     */
    showPwd(type) {
      if (this[type] === 'password') {
        this[type] = '';
      } else {
        this[type] = 'password';
      }
      this.$nextTick(() => {
        this.$refs[type].focus();
      });
    },

    /**
     * 获取验证码
     */
    getSms() {
      // 验证手机号格式
      this.$refs.ruleForm.validateField('phone', errText => {
        if (errText !== '') {
          this.$message.error(this.$t('login.inputCorrectPhone'));
          return false;
        }
        // 验证手机号是否注册过
        this.exist({ username: this.ruleForm.phone }).then(res => {
          if (res) {
            this.$message.error(this.$t('login.phoneHasBeenRegistered'));
            return false;
          } else {
            // 发送验证码
            this.sendCode(this.ruleForm.phone).then(res => {
              this.bid = res;
              // 获取验证码
              this.getCode(this.bid).then(res => {
                this.code = res;
                this.ruleForm.code = res;
                this.$refs.ruleForm.clearValidate('code');
              });
            });
            // 修改获取验证按钮状态
            this.updataButtonStatus({
              status: true,
              text: this.$t('login.sending'),
            });
            // 调定时器，倒计时
            this.countDown(60);
          }
        });
      });
    },
    /**
     * 倒计时
     */
    countDown(number) {
      if (this.timer) {
        clearInterval(this.timer);
      }
      let time = number;
      this.timer = setInterval(() => {
        time--;
        if (time === 0) {
          clearInterval(this.timer);
          this.updataButtonStatus({
            status: false,
            text: this.$t('login.resend'),
          });
        } else {
          this.codeButtonStatus.text = `${time}${this.$t('login.second')}${this.$t('login.after')}${this.$t('login.resend')}`;
        }
      }, 1000);
    },
    /**
     * 清除倒计时
     */
    clearCountDown() {
      // 还原验证码按钮默认状态
      this.updataButtonStatus({
        status: false,
        text: this.$t('login.getCode'),
      });
      // 清除倒计时
      clearInterval(this.timer);
    },
    /**
     * 更新验证码按钮状态
     */
    updataButtonStatus(params) {
      this.codeButtonStatus.status = params.status;
      this.codeButtonStatus.text = params.text;
    },
    /**
     * 登录或注册接口
     */
    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (!this.bid) {
            this.$message.error(this.$t('login.errCode'));
            return false;
          }
          this.checkCode({
            phone: this.ruleForm.phone,
            code: this.ruleForm.code,
            bid: this.bid,
          }).then(res => {
            if (res === '0') {
              this.register({
                phone: this.ruleForm.phone,
                code: this.ruleForm.code,
                bid: this.bid,
                password: dataToBase64(this.ruleForm.password),
                confirmPassword: dataToBase64(this.ruleForm.passwords),
              }).then(res => {
                if (res === '0') {
                  this.$router.push('/login');
                  this.$message.success(this.$t('login.registerSuccess'));
                } else {
                  this.$message.error(this.$t('login.registerFail'));
                  return false;
                }
              });
            } else {
              return false;
            }
          });
        } else {
          this.$message.error(this.$t('login.fromError'));
          return false;
        }
      });
    },
    // 转到登录页面
    toggle() {
      this.$router.push('/login');
      this.resetFromData();
    },
    // 校验用户名是否存在
    async exist(phone) {
      const result = await code.exist(phone);
      return result.data.exist;
    },
    // 发送验证码
    async sendCode(phone) {
      const result = await code.sendCode(phone);
      return result.data.bid;
    },
    // 获取验证码
    async getCode(bid) {
      const result = await code.getCode(bid);
      return result.data.value;
    },
    // 验证码校验
    async checkCode(data) {
      const result = await code.checkCode(data);
      return result.data.code;
    },
    // 注册
    async register(data) {
      const result = await register.register(data);
      return result.data.code;
    },
  },
};
</script>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
}
.login-wrap {
  position: relative;
  width: 520px;
  max-width: 100%;
  padding: 160px 35px 0;
  margin: 0 auto;
  overflow: hidden;
}
.title {
  font-size: 26px;
  color: $light_gray;
  margin: 0px auto 40px auto;
  text-align: center;
  font-weight: bold;
}
.menu-tab {
  text-align: center;
  padding: 0;
}
.tab {
  cursor: pointer;
  color: #666;
  text-align: right;
}
.tab span:hover {
  color: #999;
}
.login-form {
  margin-top: 29px;
  outline: none;
  .item-from {
    width: 100%;
    margin-bottom: 23px;
  }
  .code {
    position: relative;
    .codebtn {
      position: absolute;
      width: 33%;
      height: 47px;
      line-height: 47px;
      top: 0;
      bottom: 0;
      right: 10px;
      background-color: transparent;
      color: #409eff;
      border-color: transparent;
      outline: none;
      cursor: pointer;
      text-align: right;
      &:disabled,
      &:disabled:hover {
        color: #999999;
        cursor: not-allowed;
      }
    }
    &:disabled,
    &:disabled:hover {
      color: #999999;
      cursor: not-allowed;
    }
    .codebtn:hover {
      color: #eee;
    }
  }
  .block {
    display: block;
    width: 100%;
    height: 52px;
  }
  .login-btn {
    margin-top: 19px;
    height: 39px;
  }
  /deep/ .el-input__inner {
    height: 52px;
    line-height: 52px;
    -webkit-appearance: none;
    padding: 12px 5px 12px 15px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: #2d3a4b;
    border-radius: 5px;
    color: #fff;
  }
}
.show-pwd {
  position: absolute;
  right: 10px;
  top: 7px;
  font-size: 16px;
  color: $dark_gray;
  cursor: pointer;
  user-select: none;
}
</style>
